/*
This work is donated to the public domain. Make of it what you will.
*/


var req;

if (window.widget){
    widget.onshow = onshow;
    widget.onhide = onhide;
}


function onshow(){
       connect();
}


function onhide(){

}


function movieClicked(event){
    return false;
}


function connect(){
    //Clean out output.
    var child; 
    while(child = document.getElementById("output").firstChild){
	document.getElementById("output").removeChild(child);
    }

    while(child = document.getElementById("outputBack").firstChild){
	document.getElementById("outputBack").removeChild(child);
    }


    //Start the spinner
    document.getElementById("spinner").style.display = "block";

    var url;
    req = new XMLHttpRequest();
    req.onreadystatechange = handleResponse;

    url =  "http://www.netflix.com/Queue?"+(new Date()).getTime();
    req.open("GET", url, true);
    req.send(null);
}


function handleResponse(){
    if(req.readyState == 4){
	//Kill the spinner.
	document.getElementById("spinner").style.display = "none";


	if(req.status == 200) {
	    //First we're going to check to see if the title of the
	    //returned document is "Netflix: Queue".  If it's not,
	    //either Netflix has changed its page or the user is not
	    //logged in (and doesn't have the right cookies for this
	    //to work.

	    var response = req.responseText;
	    if(!response.match("<title>Netflix: Queue</title>")){
		var para = document.createElement("p");
		var text = document.createTextNode("Cannot find the cookies needed to log in to Netflix. You must use Safari log in to Netflix at least once before using this widget. ");

		var link = document.createElement("a");
		var linkText = document.createTextNode("Click here");
		link.href = "javascript:widget.openURL('http://www.netflix.com/Login')";
		link.appendChild(linkText);

		para.id = "error";
		para.appendChild(text);
		para.appendChild(link);
		
		text = document.createTextNode(" to log in now.");
		para.appendChild(text);

		document.getElementById("output").appendChild(para);	
		calculateAndShowThumb();
		return;
	    }

	    //The "." operator does not appear to be working properly.
	    //I can't make it match "\n" with /s, /m, or /sm.  And I
	    //can't group it with ANYTHING in [].  So I'm using 
	    //"[\d\D]" to mean "anything".
	    var regex = new RegExp("<tr class=\"or\">[\\d\\D]+?</tr>", "g");
	    var backref;
	    var homeMovies = new Array(0);
	    var queueMovies = new Array(0);

	    while(backref = regex.exec(response)){
		homeMovies.push(backref[0]);
	    }

	    regex = new RegExp("<tr class=\"bd\">[\\d\\D]+?</tr>", "g");
	    while(backref = regex.exec(response)){
		queueMovies.push(backref[0]);
	    }


	    if(homeMovies.length > 0){
		homeMovies = parseMovies(homeMovies);
		outputMovies(homeMovies);
	    }else{
		var para = document.createElement("p");
		var text = document.createTextNode('Cannot find any "at home" movies. Flip me over to see your Netflix queue.');
		para.appendChild(text);
		para.id = "error";
		document.getElementById("output").appendChild(para);
	    }

	    if(queueMovies.length > 0){
		queueMovies = parseQueue(queueMovies);
		outputQueue(queueMovies);
	    }else{
		var para = document.createElement("p");
		var text = document.createTextNode('Cannot find any movies in your Netflix queue.');
		para.appendChild(text);
		para.id = "error";
		document.getElementById("outputBack").appendChild(para);
	    }



	    calculateAndShowThumb();



	}else{
	    var para = document.createElement("p");
	    var text = document.createTextNode("Cannot connect to the Netflix web page. Please try again in a few moments or check your internet connection.");
	    para.appendChild(text);
	    para.id = "error";
	    document.getElementById("output").appendChild(para);
	    calculateAndShowThumb();
	}
    }		
}


function parseMovies(arr){
    var titles = new RegExp("href=\"([^\"]+)\">([^<]+)");
    var dates = new RegExp("<td class=\"ee\" colspan=\"2\">([\\d/]+)[^\\d]+([\\d/]+)");
    var count;
    var nameArr;
    var dateArr;
    var newArr = new Array(0);

    for(var i=0; i<arr.length; i++){
	//Netflix does some goofy stuff to the queue if you've ordered a replacement disk.
	
	var movieStats = new Array(0);

	nameArr = titles.exec(arr[i]);
	if(nameArr != null){
	    movieStats.push(nameArr[1]);
	    movieStats.push(nameArr[2]);
	
	    dateArr = dates.exec(arr[i]);
	    if(null == dateArr){
		movieStats.push("Unknown");
		movieStats.push("Unknown");

	    }else{
		movieStats.push(dateArr[1]);
		movieStats.push(dateArr[2]);

	    }
	
	    newArr.push(movieStats);
	}
    }

    return newArr;
}


function parseQueue(arr){
    var titles = new RegExp("href=\"([^\"]+)\">([^<]+)");
    var nameArr;
    var newArr = new Array(0);

    for(var i=0;i<arr.length; i++){
	var queueStats = new Array(0);

	nameArr = titles.exec(arr[i]);
	if(nameArr != null){
	    queueStats.push(nameArr[1]);
	    queueStats.push(nameArr[2]);

	    newArr.push(queueStats);
	}
	    
    }

    return newArr;
}


function outputQueue(arr){
    for(var i=0;i<arr.length;i++){
	var para = document.createElement("p");
	var bold = document.createElement("b");
	var number = document.createTextNode((i+1)+" ");
	var element = document.createElement("a");
	var text = document.createTextNode(arr[i][1]);
	bold.appendChild(number);
	bold.className = "queueNumber";
	element.appendChild(text);
	element.className = "movieName";
	if(window.widget){
	    element.href="javascript:widget.openURL('"+arr[i][0]+"')";
	}
	element.onmouseover = giveTheFinger;
	element.onmouseout = putItAway;
	para.appendChild(bold);
	para.appendChild(element);
	document.getElementById("outputBack").appendChild(para);
    }


}


function outputMovies(arr){
    for(var i=0; i<arr.length; i++){
	var element = document.createElement("a");
	var text = document.createTextNode(arr[i][1]);
	element.appendChild(text);
	element.className = "movieName";
	if(window.widget){
	    element.href="javascript:widget.openURL('"+ arr[i][0]  +"')";
	}
	element.onmouseover = giveTheFinger;
	element.onmouseout = putItAway;
	document.getElementById("output").appendChild(element);

	element = document.createElement("p");
	text = document.createTextNode("Est. Arrival: "+arr[i][3]);
	element.appendChild(text);
	element.className = "movieDate";
	document.getElementById("output").appendChild(element);	
    }

}


function giveTheFinger(){
    document.body.style.cursor = "hand"; 
}

function putItAway(){
    document.body.style.cursor = "default"; 
}
		
